package cn.xshi.iot.live.worker;

import cn.xshi.iot.live.util.CacheUtil;
import cn.xshi.iot.live.util.TranscribeUtil;
import cn.xshi.iot.live.model.CameraEntity;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * @Desc 录制线程类
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class TranscribePusher {

    public static class TranscribePusherRunnable implements Runnable {
        // 创建线程池
        public static ExecutorService es = Executors.newCachedThreadPool();
        private CameraEntity cameraEntity;
        private Thread nowThread;
        public TranscribePusherRunnable(CameraEntity cameraEntity) {
            this.cameraEntity = cameraEntity;
        }
        // 中断线程
        public void setInterrupted() {
            nowThread.interrupt();
        }
        // 中断线程
        public void setInterrupted(CameraEntity cameraEntity) {
            this.cameraEntity = cameraEntity;
        }
        @Override
        public void run() {
            try {
                if(cameraEntity.getErrorCount()<=100){
                    // 获取当前线程存入缓存
                    nowThread = Thread.currentThread();
                    cameraEntity.setOpenTime(new Date());//记录上次录制时间
                    // 执行转流推流任务
                    TranscribeUtil transcribeUtil = new TranscribeUtil(cameraEntity).startFrameRecord();
                    if (transcribeUtil != null) {
                        cameraEntity.setOpenTime(new Date());//记录上次录制时间
                        log.info("开始录制，进入线程："+cameraEntity.getOpenTime());
                        CacheUtil.transcribeMap.put(cameraEntity.getStream(), cameraEntity);
                        transcribeUtil.doStartFrameRecord(nowThread);
                    }
                }
                // 清除缓存
                log.info("录制视频，清理缓存对象开始...");
                CacheUtil.transcribeMap.remove(cameraEntity.getStream());
                CacheUtil.transcribeJobMap.remove(cameraEntity.getStream());
                log.info("录制视频，清理缓存对象完毕...");
            } catch (Exception e) {
                log.error("录制视频，当前任务： " + cameraEntity.getRtspUrl() + "停止...");
                CacheUtil.transcribeMap.remove(cameraEntity.getStream());
                CacheUtil.transcribeJobMap.remove(cameraEntity.getStream());
                cameraEntity.setErrorCount(cameraEntity.getErrorCount()+1);
            }finally {
                log.info("录制视频，当前任务终止，名称："+nowThread.getName()+"，ID："+nowThread.getId()+"，ErrorCount："+cameraEntity.getErrorCount()+"，当前设备编号："+cameraEntity.getErrorCount());
                log.info("录制视频重新加入保活线程中开始.....");
                if(cameraEntity.getErrorCount()<=100){
                    KeepAliveTranscribeWorker.put(cameraEntity);//进行保活
                }else{
                    log.info("录制视频终止，原因始终无法连接成功，该设备无效，ID号："+cameraEntity.getStream());
                }
            }
        }
    }
}
